package cn.shadow.module.snake;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.Array;

import java.util.Iterator;

public class Food extends Stage {
    private int initNum;
    private TextureRegion[] foods;
    private Sound sound;
    public Food(int initNum) {
        Texture texture = new Texture(Gdx.files.internal("image/food.png"));
        this.sound = Gdx.audio.newSound(Gdx.files.internal("sound/eat.mp3"));
        this.initNum = initNum;
        this.foods = createFoods(texture);
        initFoods();
    }

    private void initFoods() {
        for (int i = 0; i < initNum; i++) {
            FoodNode foodNode = FoodNode.creatFood(getWidth(), getHeight(), randFoods());
            addActor(foodNode);
        }
    }

    private TextureRegion[] createFoods(Texture texture) {
        TextureRegion[] foods = new TextureRegion[3];
        int with = texture.getWidth() / 3;
        for (int i = 0; i < 3; i++) {
            foods[i] = new TextureRegion(texture, with*i, 0, with, texture.getHeight());
        }
        return foods;
    }

    public TextureRegion randFoods() {
        int length = foods.length;
        int index = (int) (Math.random() * length);
        return foods[index];
    }


    @Override
    public void act() {
        super.act();
    }

    public void eatFood(Snake snake) {
        Array<Actor> snakes = snake.getActors();
        for (Actor snakeActor : snakes) {
            SnakeNode snakeNode = (SnakeNode) snakeActor;
            Array<Actor> foods = getActors();
            for (Iterator<Actor> iterator = foods.iterator(); iterator.hasNext(); ) {
                FoodNode foodNode = (FoodNode) iterator.next();
                if (!snakeNode.isHead()) {
                    continue;
                }
                if (foodNode.canEat(snakeNode.getX(), snakeNode.getY(), snakeNode.getWidth() / 2.0f)) {
                    sound.play();
                    snake.growUp(foodNode.getRegion());
                    iterator.remove(); //移掉旧的
                    System.out.println("蛇吃掉了一个食物");
                    newFood(); //产生新的
                }
            }
            break;
        }
    }

    public void newFood() {
        FoodNode newFood = FoodNode.creatFood(getWidth(), getHeight(), randFoods());
        this.getActors().add(newFood);
        System.out.println("产生了一个食物");
    }
    public void reset() {
        Group root = getRoot();
        root.clear();
        initFoods();
    }

    public Sound getSound() {
        return sound;
    }

    public void setSound(Sound sound) {
        this.sound = sound;
    }
}